<template>
  <!-- 知识管理-实体管理页面 -->
  <el-row :gutter="20" class="entity-manage">
    <el-col :span="5" class="entity-type">
      <type-tree :tree-data="optionsType" @select-node="updateEntityType" />
    </el-col>
    <el-col :span="19" class="entity-list">
      <div class="server-main">
        <el-form :inline="true" v-model="metaData" class="search-form">
          <el-form-item label="实体名称" class="form-input">
            <el-input
              v-model="metaData.searchVal"
              placeholder="请输入内容"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" class="status form-input">
            <el-select v-model="metaData.status">
              <el-option label="全部" value="2"></el-option>
              <el-option label="启用" value="0"></el-option>
              <el-option label="禁用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="onSubmit"
              style="width: 60px; height: 32px; padding: 0"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <div class="server-table">
          <div class="table-title">
            <span class="table-title-text">实体管理</span>
            <el-button type="primary" size="small" @click="openDia"
              >新增实体</el-button
            >
          </div>
          <el-table
            :data="tableList"
            class="map-manage"
            size="medium"
            v-loading="loading"
            :header-cell-style="{ background: '#F3F4F8', color: '#000000' }"
            :cell-style="{ color: '#333333' }"
          >
            <el-table-column
              type="index"
              prop="id"
              label="ID"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column prop="entityName" label="实体名称" align="center">
              <template slot-scope="scope">
                <img
                  :src="scope.row.entityName"
                  v-if="scope.row.entityStatus == 1"
                  style="width: 80px"
                />
                <el-popover
                  placement="top-start"
                  width="100"
                  trigger="hover"
                  v-else
                  :content="scope.row.entityName"
                >
                  <span slot="reference">{{ scope.row.entityName }}</span>
                </el-popover>
              </template></el-table-column
            >
            <el-table-column
              prop="ontologyName"
              show-overflow-tooltip
              label="所属类别"
              align="right"
            ></el-table-column>
            <el-table-column
              prop="confidence"
              label="实体置信度"
              width="160"
              align="right"
            ></el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <i
                  class="little-circle-blue"
                  v-if="scope.row.status == '0'"
                ></i>
                <i class="little-circle-red" v-else></i>
                <span>{{ scope.row.status == "0" ? "启用" : "禁用" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="180"
              fixed="right"
              align="center"
              class="operation"
            >
              <template slot-scope="scope">
                <el-link
                  class="handle-button"
                  :underline="false"
                  type="primary"
                  @click.native.prevent="goDetail('view', scope.row.entityId)"
                  >查看</el-link
                >
                <el-link
                  :underline="false"
                  class="handle-button"
                  style="
                    padding: 0 10px;
                    border-left: 1px solid #ddd;
                    border-right: 1px solid #ddd;
                  "
                  type="primary"
                  @click.native.prevent="goDetail('edit', scope.row.entityId)"
                  >编辑</el-link
                >
                <el-link
                  :underline="false"
                  class="handle-button"
                  type="primary"
                  @click.native.prevent="changeStatus(scope.row)"
                  >{{ scope.row.status == "0" ? "禁用" : "启用" }}</el-link
                >
              </template>
            </el-table-column>
            <!-- <template slot="append" class="table-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :hide-on-single-page="!total"
            :page-size="metaData.pageSize"
            :pager-count="11"
            :current-page="metaData.page"
            prev-text="上一页"
            next-text="下一页"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </template> -->
          </el-table>
          <div class="pagination">
            <el-pagination
              class="table-pagination"
              :small="true"
              background
              layout="total, prev, pager, next,sizes, jumper"
              :total="total"
              :hide-on-single-page="!total"
              :page-size="metaData.pageSize"
              :pager-count="5"
              :page-sizes="[10, 20, 30]"
              :current-page="metaData.page"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          width="560px"
          class="map-dialog common-dialog"
          :show-close="false"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
        >
          <el-form
            :model="mapForm"
            :rules="rules"
            label-width="100px"
            class="entity-form"
            ref="addEntityDia"
          >
            <el-form-item label="实体名称" prop="name">
              <el-input v-model="mapForm.name"></el-input>
            </el-form-item>
            <el-form-item label="实体类别" prop="entityType">
              <el-cascader
                v-model="mapForm.entityType"
                change-on-select
                class="map-descri"
                placeholder=""
                :options="optionsType"
                clearable
                @change="handleChange"
                filterable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="置信度" prop="percentage">
              <el-input-number
                v-model="mapForm.percentage"
                :step="0.1"
                suffix-icon="el-icon-date"
              >
              </el-input-number>
              <!-- <span style="position: absolute">%</span> -->
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </el-dialog>
        <router-view></router-view>
      </div>
    </el-col>
  </el-row>
</template>
<script>
import { EventBus } from "@/views/server/knowledge-management/eventBus";
import TypeTree from "./components/TypeTree.vue";
import { mapState } from "vuex";
//置信度校验
const checkPercentage = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("置信度不能为空"));
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error("请输入数字值"));
    } else {
      if (value < 0 || value > 100) {
        callback(new Error("0~100"));
      } else {
        callback();
      }
    }
  }, 0);
};
const checkType = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("实体类别不能为空！"));
  }
};
export default {
  name: "MapManagement",
  components: { TypeTree },
  data: () => {
    const formatCheck = (rule, value, callback) => {
      if (!/^(0|1|(0\.\d{1,4}))$/g.test(value)) {
        callback(new Error("置信度只能是0或1或0~1之间的小数,小数最多四位"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false, // 弹框的开关
      title: "新增实体", // 弹框名称
      mapForm: {
        name: "",
        entityType: [],
        percentage: 1,
      },
      selectKnowledge: "", // 选中的图谱的数据
      rules: {
        name: [
          { required: true, message: '请输入实体名称', trigger: ['blur', 'change']  },
        ],
        entityType: [
          { required: true, message: '请选择实体类别', trigger: ['blue', 'change']  },
          { validator: checkType, trigger: ['blur', 'change'] }
        ],
        percentage: [
          { validator: formatCheck, trigger: ['blur', 'change'] },
          { required: true, message: '置信度不能为空'},
          { type: 'number', message: '置信度值必须为数字值' },
        ],
        // percentage: [
        //   {
        //     trigger: "blur",
        //     validator: formatCheck,
        //   },
        // ],
      },
      metaData: {
        searchType: null,
        searchVal: "", // 图谱名称
        status: "2", // 状态
        page: 1, // 页码
        pageSize: 10, // 每页条数
      },
      optionsType: [],
      tableList: [], // 事件素材列表
      total: 0, // 数据总条数
      loading: false,
    };
  },
  computed: {},
  created() {
    this.$nextTick(() => {
      EventBus.$on("selectKnowledge", (val) => {
        this.selectKnowledge = val;
        // this.mapTree();
        this.getEntityList();
      });
    });
    // this.mapTree();
  },
  beforeDestroy() {
    EventBus.$off("selectKnowledge");
  },
  methods: {
    // 实体类变更
    updateEntityType(node) {
      this.metaData.searchType = node.value;
      this.onSubmit();
    },
    getEntityList() {
      this.loading = true;
      let params = {
        projectId: this.selectKnowledge.projectId,
        ontologyId: this.metaData.searchType,
        entityName: this.metaData.searchVal,
        status: this.metaData.status,
        pageNum: this.metaData.page,
        pageSize: this.metaData.pageSize,
      };
      this.$axios
        .post(this.$api.knowledgeMap.getEntityList, params)
        .then((res) => {
          const { data, message, code } = res.data;
          if (code === 200) {
            this.tableList = data.list;
            this.total = data.total;
          } else {
            this.$message.warning(message);
          }
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 删除children:[]项
    hideSubPanelData(obj) {
      if (Array.isArray(obj)) {
        obj.length > 0 &&
          obj.map((item) => {
            if (item.children.length === 0) {
              delete item.children;
            } else {
              this.hideSubPanelData(item.children);
            }
          });
      } else {
        this.$message.warning("数据格式出错");
      }
      return obj;
    },
    // 设置实体状态
    setEntityStatus(id, type) {
      type = type == "0" ? 1 : 0;
      let params = {
        entityId: id,
        status: type,
      };
      this.$axios
        .post(this.$api.knowledgeMap.setEntityStatus, params)
        .then((res) => {
          const { data, code, message } = res.data;
          if (code === 200) {
            this.getEntityList();
            this.$message.success(`${type === 0 ? "启用" : "禁用"}成功`);
            return;
          }
          this.$message.warning(message);
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    addEntity() {
      console.log(999999, this.mapForm);
      if (!(this.mapForm.name && this.mapForm.entityType.length > 0)) {
        this.$message.warning("请填写完整信息！");
        return;
      }
      if (
        this.mapForm.percentage &&
        !this.validConfidence(this.mapForm.percentage)
      ) {
        this.$message.warning("置信度只能是0或1或0~1之间的小数,小数最多四位");
        return;
      }
      let params = {
        projectId: this.$store.state.knowledgeMap.projectMsg.projectId,
        ontologyId: this.mapForm.entityType[this.mapForm.entityType.length - 1],
        entityName: this.mapForm.name,
        confidence: this.mapForm.percentage.toString(),
      };
      this.$axios
        .post(this.$api.knowledgeMap.addEntity, params)
        .then((res) => {
          const { data, code, message } = res.data;
          if (code === 200) {
            this.dialogVisible = false;
            this.getEntityList();
            this.mapForm.name = "";
            this.mapForm.percentage = 1;
            this.mapForm.entityType = [];
          } else {
            this.$message.warning(message);
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 检验输入数据是否是数字
    isNumber(val) {
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg =
        /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true;
      } else {
        return false;
      }
    },
    validConfidence(val) {
      if (!/^(0|1|(0\.\d{1,4}))$/g.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    changeStatus(id) {
      this.$confirm(
        `是否${id.status === "0" ? "禁用" : "启用"}当前实体`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.setEntityStatus(id.entityId, id.status);
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    // 查询交互
    onSubmit() {
      this.getEntityList();
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.metaData.page = page;
      this.getEntityList();
    },
    handleSizeChange(size) {
      this.metaData.pageSize = size;
      this.getEntityList();
    },
    // 跳转详情页
    goDetail(type, id) {
      if (type === "view") {
        this.$router.push({
          path: "/manage/entityManagement/view",
          query: {
            id: id,
          },
        });
      }
      if (type === "edit") {
        this.$router.push({
          path: "/manage/entityManagement/edit",
          query: {
            id: id,
          },
        });
      }
    },
    openDia() {
      this.dialogVisible = true;
      this.title = "新增实体";
    },
    save() {
      this.addEntity();
    },
    cancel() {
      this.dialogVisible = false;
      this.$refs.addEntityDia.resetFields();
    },
    mapTree() {
      let params = {
        projectId: this.$store.state.knowledgeMap.projectMsg.projectId,
      };
      this.$axios
        .post(this.$api.knowledgeMap.mapTree, params)
        .then((res) => {
          const { data, message, code } = res.data;
          if (code == 200) {
            this.hideSubPanelData(data);
            this.optionsType = data;
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    handleChange() {},
  },
  watch: {
    "$store.state.knowledgeMap.projectMsg.projectId": {
      handler(val, old) {
        if (val !== old) {
          this.mapTree();
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.entity-manage {
  position: relative;
  height: 100%;
  padding-bottom: 24px;
  box-sizing: border-box;
}
.entity-type,
.entity-list {
  height: 100%;
}

.server-main {
  height: 100%;

  .search-form {
    min-height: 72px;
    padding: 0 32px;
    background: #ffffff;
    border-radius: 4px;
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;

    .el-form-item {
      margin-bottom: 0;
      margin-right: 32px;
    }
  }

  .form-input {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
    }
  }

  .server-table {
    background: #ffffff;
    padding: 16px 32px 20px;
    min-height: calc(100% - 136px);

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid #4b71eb;
        padding-left: 10px;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .el-table {
      .operation {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }
    }

    /deep/ .cell {
      text-align: center;
    }

    .handle-button {
      margin-right: 10px;
    }
  }
}

.pagination {
  position: relative;
  margin-top: 28px;
  height: 40px;

  .table-pagination {
    position: absolute;
    right: 0;

    /deep/ .el-input__inner {
      height: 22px;
    }
  }
}

.little-circle-blue {
  width: 6px;
  height: 6px;
  background: #55c898;
  display: inline-block;
  border-radius: 6px;
  line-height: 6px;
  margin-right: 6px;
  margin-bottom: 2px;
}

.little-circle-red {
  width: 6px;
  height: 6px;
  background: #ee5564;
  display: inline-block;
  border-radius: 6px;
  line-height: 6px;
  margin-right: 6px;
  margin-bottom: 2px;
}

.map-dialog {
  .form-select {
    width: 100%;
  }

  .form-link {
    line-height: initial;
  }

  /deep/ .el-dialog__header {
    border-bottom: 2px solid #e5e6e9;
  }

  /deep/ .el-dialog__body {
    padding-bottom: 0;
  }

  .map-descri {
    width: 100%;
  }
  /deep/ .el-input-number {
    width: 100%;
  }
  /deep/ .el-input-number__decrease {
    display: none;
  }
  /deep/ .el-input-number__increase {
    display: none;
  }
}

.common-dialog {
  /deep/ .el-dialog {
    border-radius: 4px;
  }

  /deep/ .el-dialog__header {
    padding: 20px;
    padding-left: 32px;
  }

  /deep/ .el-dialog__title {
    font-size: 18px;
    font-family: MicrosoftYaHeiUI-Bold, MicrosoftYaHeiUI;
    color: #333333;
  }

  /deep/ .el-dialog__body {
    padding: 42px 60px 0 60px;
  }

  /deep/ .el-input__inner {
    height: 32px;
  }

  /deep/ .el-form-item__label {
    color: #333333;
  }

  /deep/ .el-button {
    width: 68px;
    height: 32px;
    padding: 6px;
    margin-left: 16px;
    border: 1px solid #e0e0e0;
    border-radius: 0;
  }
}

/deep/ .el-input-number .el-input__inner {
  text-align: left;
  padding: 0 15px;
}
</style>
